import cv2
import numpy as np

def cv_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
"""
img = cv2.imread('C:/Users/nic/Desktop/opencv/picture/cat.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
#得到特征值
sift = cv2.SIFT_create()
kp = sift.detect(gray,None)
img = cv2.drawKeypoints(gray,kp,img)
cv_show('corner',img)
#计算特征
kp,des = sift.compute(gray,kp)
#特征匹配
"""

img1 = cv2.imread('C:/Users/nic/Desktop/opencv/picture/cat.jpg')
img2 = cv2.imread('C:/Users/nic/Desktop/opencv/picture/templet_cat.jpg')
sift = cv2.SIFT_create()
kp1,des1 = sift.detectAndCompute(img1,None)
kp2,des2 = sift.detectAndCompute(img2,None)
"""
#one by one match
bf = cv2.BFMatcher(crossCheck=True)
matches = bf.match(des1,des2)
matches = sorted(matches,key=lambda x:x.distance)
image3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:50],None,flags=2)
cv_show('match',image3)
"""
#k对最佳匹配
bf = cv2.BFMatcher()
matches = bf.knnMatch(des1,des2,k=2)
#过滤
good = []
for m,n in matches:
    if m.distance < 0.8*n.distance:
        good.append([m])
image4 = cv2.drawMatchesKnn(img1,kp1,img2,kp2,good,None,flags=2)
cv_show('match',image4)
